<?php
namespace app\admin\controller;
use think\facade\Db;
class GoodsCate extends Adm
{
	use \app\admin\traits\Curd;
    public function index()
    {
    	return $this->fetch();
    }
    /**
     * [_add 扩展]
     * 
     */
    protected function _add()
    {
        $cates = ($this->_model)::select()->toArray();
        $cates = $this->arrtotreelist($cates,'parent_id');
        $this->assign(get_defined_vars());
    }
    //获取所有分类
    public function all()
    {
    	$data = ($this->_model)::select()->toArray();
    	//$data = $this->arrtotreelist($data,'parent_id');
    	$count = null;
    	$this->assign(get_defined_vars());
    	$this->code = 0;
    	return $this->fetch();
    }
    public function selectParent()
    {
        header('Content-Type:application/json; charset=utf-8');
        $data = Db::name('goods_cate')->select();
        $data[] = [
            "id"=>"0",
            "name"=>"顶级分类",
            "pid"=>"-1",
            "sort"=>null
        ];
        $response = [
            'status'=>[
                'code'=>'200',
                'msessage'=>''
            ],
            'data'=>$data
        ];
        return json($response);
    }
    //添加测试数据
    public function addtestdata()
    {
        $testdata = '[{"name":"文具","id":1,"pid":0,"level":1},{"name":"专场推荐","id":2,"pid":0,"level":1},{"name":"热门分类","id":3,"pid":0,"level":1},{"name":"晨光","id":4,"pid":1,"level":2},{"name":"小米","id":5,"pid":1,"level":2},{"name":"得力","id":6,"pid":1,"level":2},{"name":"英雄","id":7,"pid":1,"level":2},{"name":"百乐","id":8,"pid":1,"level":2},{"name":"中性笔","id":9,"pid":4,"level":3},{"name":"铅笔","id":10,"pid":4,"level":3},{"name":"小米中性笔","id":11,"pid":5,"level":3},{"name":"小米铅笔","id":12,"pid":5,"level":3},{"name":"得力中性笔","id":13,"pid":6,"level":3},{"name":"英雄钢笔","id":14,"pid":7,"level":3},{"name":"百乐钢笔","id":15,"pid":8,"level":3}]';
        $testdata = json_decode($testdata);
        foreach ($testdata as $k => $v) {
            Db::name('goods_cate')->insert([
                'name'=>$v->name,
                'id'=>$v->id,
                'pid'=>$v->pid,
                'level'=>$v->level
            ]);
        }
    }
    private function arrtotreelist($lists,$parent_field='parent_id',$parent_id=0)
    {
    	$list = [];
    	$rows = $lists;
    	foreach($rows as $k=>$v)
    	{
    		if($v['parent_id']==$parent_id)
    		{
    			array_push($list, $v);
    			unset($lists[$k]);
    			$sons = $this->arrtotreelist($lists,$parent_field,$v['id']);
    			foreach($sons as $i=>$item){
    				array_push($list, $item);
    			}
    		}
    	}
    	return $list;
    }
}
